/**
 * 
 */
package info.niwota.commons;

import info.niwota.commons.io.Files;

import java.io.File;
import java.util.Comparator;

/**
 * @author qiangli
 * 
 */
public class FileComparator implements Comparator<File> {
	private int sort = 0;
	private int dir = 1;

	public FileComparator() {
	}

	public FileComparator(String sort, boolean asc) {
		this.sort = convert(sort);
		this.dir = (asc ? 1 : -1);
	}

	private int convert(String s) {
		if (s == null) {
			return 0;
		}
		s = s.toLowerCase();
		if (s.equals("name")) {
			return 0;
		}
		if (s.equals("type")) {
			return 1;
		}
		if (s.equals("size")) {
			return 2;
		}
		if (s.equals("date")) {
			return 3;
		}
		return 0;
	}

	public int compare(File f1, File f2) {
		if (f1 == null) {
			return -dir;
		}
		if (f2 == null) {
			return dir;
		}
		switch (sort) {
		case 1:
			String t1 = Files.fileExt(f1.getName());
			if (t1 == null) {
				return -dir;
			}
			String t2 = Files.fileExt(f2.getName());
			if (t2 == null) {
				return dir;
			}
			return t1.compareTo(t2) * dir;
		case 2:
			return (int) (f1.length() - f2.length()) * dir;
		case 3:
			return (int) (f1.lastModified() - f2.lastModified()) * dir;
		case 0:
		default:
		}
		String n1 = f1.getName();
		if (n1 == null) {
			return -dir;
		}
		String n2 = f2.getName();
		if (n2 == null) {
			return dir;
		}
		return n1.compareTo(n2) * dir;
	}
}
